package com.cssy.xxkj.logic.web;

import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicProductBomDO;
import com.cssy.xxkj.basic.entity.BasicProductBomProcessDO;
import com.cssy.xxkj.basic.entity.BasicSeriesDO;
import com.cssy.xxkj.basic.service.IBasicMaterialsBomService;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchDO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchItemDO;
import com.cssy.xxkj.logic.entity.LogicProductionPlanDO;
import com.cssy.xxkj.logic.entity.LogicProductionPlanItemDO;
import com.cssy.xxkj.logic.service.ILogicProductionDispatchService;
import com.cssy.xxkj.logic.service.ILogicProductionPlanService;
import com.cssy.xxkj.logic.util.OftenMothedUtil;
import com.cssy.yd.logic.util.MathUtil;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.json.OutJsonGrid;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 生产调度控制器
 * @author hf
 *
 */
@Controller
@RequestMapping("/logic/prodispatch")
public class ProductionDispatchController extends BaseController<LogicProductionDispatchDO> {

	private static final Logger logger = Logger.getLogger(ProductionDispatchController.class);

	private static final String MANAGER = "/xxkj/logic/productiondispatch/ProDispatchManager";// 列表页面
	private static final String EIDT = "/xxkj/logic/productiondispatch/ProDispatchOperation";// 添加、修改、显示页面

	@Resource(name = "logicProductionDispatchService")
	private ILogicProductionDispatchService logicProductionDispatchService;
	//生产计划Service
	@Resource(name = "logicProductionPlanService")
	private ILogicProductionPlanService logicProductionPlanService;

	@Resource(name="basicMaterialsBomService")
	private IBasicMaterialsBomService basicMaterialsBomService;
	//主数据公用集合Service
	@Resource(name="basicUtilService")
	private IBasicUtilService basicUtilService;

	@Resource(name = "oftenMothedUtil")
	private OftenMothedUtil oftenMothedUtil;

	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs=this.oftenMothedUtil.getNoFinishConditions(scs, "zd008Billstatus",
				BillStatusUtil.PRODISPATCH_BILL_STATUS_TWO);
		scs.setOrderBy("bizCreatorDate desc");
		SearchResult result = logicProductionDispatchService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		if (OperationFlag.ADD.equals(flag)) {// 新增加时操作
			model.addAttribute("flag", "ADD");
		} else {
			LogicProductionDispatchDO dispat = logicProductionDispatchService.findListById(id);
			model.addAttribute("prodispat", dispat);
		}
		return EIDT;
	}

	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions dspathScs = new SearchConditions();
		dspathScs.setRemovedProperty(null);
		hander.getWheres(dspathScs);
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicProductionDispatchDO prodispat = logicProductionDispatchService.findListById(id);
			dspathScs.addCondition("zd001ProDispatId", prodispat.getId(), SearchCondition.OP_EQUAL);
			List<LogicProductionDispatchItemDO> soitem = logicProductionDispatchService.findItemListByExample(dspathScs);
			OutJsonGrid out = new OutJsonGrid(soitem);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicProductionDispatchDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String itemdata = request.getParameter("itemdata");
			if (StringUtils.isBlank(itemdata)) {
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			logicProductionDispatchService.dispatSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields = ids.split(",");
			for (String field : fields) {
				LogicProductionDispatchDO ld = logicProductionDispatchService.findListById(field);
				logicProductionDispatchService.deleteBizRemoved(ld.getId());
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());

		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@RequestMapping("/gridBomitems")
	public void gridBomitems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			List<LogicProductionDispatchItemDO> list = new ArrayList<LogicProductionDispatchItemDO>();
			LogicProductionPlanDO proplan = logicProductionPlanService.findListById(id);
			List<LogicProductionPlanItemDO> proplanitem = logicProductionPlanService.findPlanItemList(proplan.getId());
			if(proplanitem!=null&&!proplanitem.isEmpty()&&proplanitem.size()>0){
				for(int i=0;i<proplanitem.size();i++){
					SearchConditions scs = new SearchConditions();
					scs.setRemovedProperty("removed");
					scs.addCondition("zd008MaterialsId", proplanitem.get(i).getZd006MaterialsId(),SearchCondition.OP_EQUAL);
					SearchResult result = basicMaterialsBomService.findListByExample(scs);
					List<BasicProductBomDO> bomlist = result.getResults();
					if(bomlist!=null&&!bomlist.isEmpty()&&bomlist.size()>0){
						//产品维护了bom
						BasicProductBomProcessDO bdo = new BasicProductBomProcessDO();
						bdo.setZd001BomId(bomlist.get(0).getId());
						List<BasicProductBomProcessDO> bomprocesslist = basicMaterialsBomService.processList(bdo).getResults();
						if(bomprocesslist!=null&&!bomprocesslist.isEmpty()&&bomprocesslist.size()>0){
					    	list.addAll(this.bomConvert(bomprocesslist, proplanitem.get(i),proplan.getZd001FormCode()));
					    }
					}else{
						//产品没有维护bom，根据产品系列的bom来生成
						Map<String, String> xlMap = this.getSeriesMap();
						if(xlMap==null||xlMap.get(proplan.getZd002OriType())==null){
							continue;
						}
						BasicProductBomProcessDO bomprocessDO = new BasicProductBomProcessDO();
						bomprocessDO.setZd001BomId("XL"+xlMap.get(proplan.getZd002OriType()));
						List<BasicProductBomProcessDO> bomprocessList = basicMaterialsBomService.processList(bomprocessDO).getResults();
						if(bomprocessList!=null&&!bomprocessList.isEmpty()&&bomprocessList.size()>0){
							list.addAll(this.bomConvert(bomprocessList, proplanitem.get(i),proplan.getZd001FormCode()));
						}
					}
				}
			}
			OutJsonGrid out = new OutJsonGrid(list);
			out.printJSon(response);
		}
	}

	private Map<String, String> getQuerySeriesToMap(){
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		List<BasicSeriesDO> srsList = basicUtilService.resultSeries(scs);
		if(srsList==null||srsList.isEmpty()||srsList.size()==0){
			return null;
		}else{
			Map<String, String> srsMap = new HashMap<String, String>();
			for(BasicSeriesDO bsrEn : srsList){
				if(bsrEn==null||StringUtils.isBlank(bsrEn.getId())){
					continue;
				}
				srsMap.put(bsrEn.getId(), bsrEn.getId());
			}
			return srsMap;
		}
	}

	private Map<String, String> getSeriesMap(){
		Map<String, String> seriesMap = new HashMap<String, String>();
		//套床
		seriesMap.put("BT", "10002");
		//床垫
		seriesMap.put("MT", "10004");
		return seriesMap;
	}

	/**
	 * 转化BOM到生产调度
	 * @param bomprocesslist
	 * @param logicProductionPlanItemDO
	 * @return
	 * @throws Exception
	 */
	private  List<LogicProductionDispatchItemDO>  bomConvert(List<BasicProductBomProcessDO> bomprocesslist,LogicProductionPlanItemDO logicProductionPlanItemDO,String plan)throws Exception{
		List<LogicProductionDispatchItemDO> list = new ArrayList<LogicProductionDispatchItemDO>();
		List<LogicProductionDispatchItemDO> ylist =this.listItem(plan);
		for(int i=0;i<bomprocesslist.size();i++){
			LogicProductionDispatchItemDO dispat = new LogicProductionDispatchItemDO();
			dispat.setZd006MaterialsId(logicProductionPlanItemDO.getZd006MaterialsId());
			dispat.setZd006MaterialsCode(logicProductionPlanItemDO.getZd007MaterialsCode());
			dispat.setZd006MaterialsName(logicProductionPlanItemDO.getZd008MaterialsName());
			dispat.setZd009MaterialsBatch(logicProductionPlanItemDO.getZd009MaterialsBatch());
			dispat.setZd010MaterialsModel(logicProductionPlanItemDO.getZd010MaterialsModel());
			dispat.setZd011MaterialsSpec(logicProductionPlanItemDO.getZd011MaterialsSpec());
			dispat.setZd012MaterialsUnit(logicProductionPlanItemDO.getZd012MaterialsUnit());
			dispat.setZd014Price(bomprocesslist.get(i).getZd010ProcessingPrice());
			dispat.setZd016ProductionQuantity(this.getProductionQuantity(ylist, bomprocesslist.get(i).getZd002ProcessId()));
			dispat.setZd021MaterialsDescription(logicProductionPlanItemDO.getZd036MaterialsDescription());
			dispat.setZd023MaterialsSize(logicProductionPlanItemDO.getZd038MaterialsSize());
			dispat.setZd026MaterialsColor(logicProductionPlanItemDO.getZd041MaterialsColor());
			dispat.setZd027MaterialsQuality(logicProductionPlanItemDO.getZd042MaterialsQuality());
			dispat.setZd028WorkShop(bomprocesslist.get(i).getBasicProcessDO().getBasicWorkshopDO().getId());
			dispat.setZd028WorkShopName(bomprocesslist.get(i).getBasicProcessDO().getBasicWorkshopDO().getZd002Name());
			dispat.setZd029Process(bomprocesslist.get(i).getZd002ProcessId());
			dispat.setZd029ProcessName(bomprocesslist.get(i).getBasicProcessDO().getZd002Name());
			dispat.setZd030PlanQuantity(logicProductionPlanItemDO.getZd013Quantity());
			dispat.setBasicProcessDO(bomprocesslist.get(i).getBasicProcessDO());
			dispat.setBasicWorkshopDO(bomprocesslist.get(i).getBasicProcessDO().getBasicWorkshopDO());
			if(dispat.getZd016ProductionQuantity().compareTo(new BigDecimal(0.0))==1){
				BigDecimal bg =MathUtil.mathUtil.subtract(dispat.getZd030PlanQuantity(), dispat.getZd016ProductionQuantity());
				dispat.setZd013Quantity(bg);
			 }else{
				dispat.setZd013Quantity(dispat.getZd030PlanQuantity());
			}
			if(dispat.getZd013Quantity().compareTo(new BigDecimal(0.0))==1){
		    	list.add(dispat);
		    }
		}
		return list;
	}

	/**
	 * 查询当前生产计划单已派工的物料
	 */
	private List<LogicProductionDispatchItemDO> listItem(String plan)
			throws Exception {
		List<LogicProductionDispatchItemDO> list = new ArrayList<LogicProductionDispatchItemDO>();
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty("removed");
		scs.addCondition("zd002OriCode", plan, SearchCondition.OP_EQUAL);
		List<LogicProductionDispatchDO> result = logicProductionDispatchService.findListByExample(scs).getResults();
		if(result!=null&&!result.isEmpty()&&result.size()>0){
			for(int i=0;i<result.size();i++){
				List<LogicProductionDispatchItemDO> dispatItem = logicProductionDispatchService.findDispatItemList(result.get(i).getId());
				list.addAll(dispatItem);
			}
		}
		return list;
	}

	private BigDecimal getProductionQuantity(List<LogicProductionDispatchItemDO> list,String proess){
		BigDecimal big = new BigDecimal(0.0);
		if(list!=null&&!list.isEmpty()&&list.size()>0){
			for(int i=0;i<list.size();i++){
				if(list.get(i).getZd029Process().equals(proess)){
					big=MathUtil.mathUtil.addtract(big, list.get(i).getZd013Quantity());
				}
			}
		}
		return big;
	}
}
